package com.chenjinyan.controller;


import com.alibaba.fastjson.JSONObject;
import com.chenjinyan.entity.GoodsEntity;
import com.chenjinyan.entity.MessageEntity;
import com.chenjinyan.entity.PicUrlEntity;
import com.chenjinyan.entity.UserEntity;
import com.chenjinyan.service.GoodsService;
import com.chenjinyan.utils.*;
import com.chenjinyan.vo.AnswerVo;
import com.chenjinyan.vo.GoodsInfoVo;
import com.chenjinyan.vo.MessageVo;
import com.chenjinyan.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author chenjinyan
 * @version 1.0
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @Autowired
    private ExceptionHandle exceptionHandle;
    @Autowired
    GoodsService goodsService;

    @Value("${server.port}")
    //获取主机端口
    private String post;

    @Value("${server.host}")
    //获取主机ip
    private String host;


    /*@Value("${lost.goods.save.path}")
    //获取主机端口
    private String path;*/

    @PostMapping("/img/upload")
    public Result uploadImg(HttpServletRequest request, @RequestParam(value = "file1", required = false) MultipartFile multipartFile1, @RequestParam(value = "file2", required = false) MultipartFile multipartFile2, @RequestParam(value = "file3", required = false) MultipartFile multipartFile3,
                            @Validated @RequestParam("username") String username, @Validated @RequestParam("typeOfGoods") Integer typeOfGoods,
                            @Validated @RequestParam("infoTittle") String infoTittle, @Validated @RequestParam("description") String description,
                            @Validated @RequestParam("lostPlace") String lostPlace, @Validated @RequestParam("lostTime") Long lostTime,
                            @Validated @RequestParam("concPlace") String concPlace, @Validated @RequestParam("concPersion") String concPersion,
                            @Validated @RequestParam(value = "phoneNo", required = false, defaultValue = "") String phoneNo, @Validated @RequestParam(value = "email", required = false, defaultValue = "") String email,
                            @Validated @RequestParam("telPhoneNo") String telPhoneNo, @Validated @RequestParam(value = "msn", required = false, defaultValue = "") String msn,
                            @Validated @RequestParam(value = "qq", required = false, defaultValue = "") String qq, @Validated @RequestParam("thankWay") Integer thankWay,
                            @Validated @RequestParam(value = "thankMoneyAmount", required = false, defaultValue = "0.00") BigDecimal thankMoneyAmount,
                            @Validated @RequestParam("goodsWay") Integer goodsWay,
                            @Validated @RequestParam(value = "findGoodsQuestion1", required = false, defaultValue = "") String findGoodsQuestion1,
                            @Validated @RequestParam(value = "findGoodsQuestion2", required = false, defaultValue = "") String findGoodsQuestion2,
                            @Validated @RequestParam(value = "findGoodsQuestion3", required = false, defaultValue = "") String findGoodsQuestion3,
                            @Validated @RequestParam(value = "findGoodsAnswer1", required = false, defaultValue = "") String findGoodsAnswer1,
                            @Validated @RequestParam(value = "findGoodsAnswer2", required = false, defaultValue = "") String findGoodsAnswer2,
                            @Validated @RequestParam(value = "findGoodsAnswer3", required = false, defaultValue = "") String findGoodsAnswer3,
                            @Validated @RequestParam(value = "province") Integer province, @Validated @RequestParam(value = "city") Integer city,
                            @Validated @RequestParam(value = "district") Integer district, @Validated @RequestParam(value = "goodsStatus", defaultValue = "0") Integer goodsStatus) {
        logger.info("******图片上传接口开始******");
        Result result = ResultUtil.success();
        List<String> list = new ArrayList<>();
        if (StringUtils.isEmpty(username)) {
            throw new DescribeException(ExceptionEnum.USER_NAME_IS_NULL);
        }
        //String path = request.getSession().getServletContext().getRealPath("/") + "/images/upload/";
        String path = "/pic/goods/images/upload";

        logger.info("图片保存路径是: " + path);
        try {
            UserEntity userEntity = goodsService.getUserIdByUsername(username);
            if (null == userEntity) {
                throw new DescribeException(ExceptionEnum.USER_NAME_IS_NULL);
            }
            //获取本机ip
            //String host = InetAddress.getLocalHost().getHostAddress();
            //String host =getIP();
            //String host = "47.102.139.16";
            //String host = "192.168.2.57";
            String savePath = "http://" + host + ":" + post + "/pic/goods/images/upload/";
            if (null != multipartFile1) {
                //保存图片到服务器
                String reqPath = ImageUtil.saveImg(multipartFile1, path, username, savePath);
                list.add(reqPath);
            }
            if (null != multipartFile2) {
                //保存图片到服务器
                String reqPath = ImageUtil.saveImg(multipartFile2, path, username, savePath);
                list.add(reqPath);
            }
            if (null != multipartFile3) {
                //保存图片到服务器
                String reqPath = ImageUtil.saveImg(multipartFile3, path, username, savePath);
                list.add(reqPath);
            }

            //保存失物实体
            GoodsEntity goodsEntity = new GoodsEntity();
            goodsEntity.setUserId(userEntity.getId());
            goodsEntity.setTypeOfGoods(typeOfGoods);
            goodsEntity.setInfoTittle(infoTittle);
            goodsEntity.setDescription(description);
            goodsEntity.setLostPlace(lostPlace);
            goodsEntity.setCreateTime(new Date());
            Date lostDate = new Date(lostTime);
            goodsEntity.setLostTime(lostDate);
            goodsEntity.setConcPlace(concPlace);
            goodsEntity.setConcPersion(concPersion);
            goodsEntity.setPhoneNo(phoneNo);
            goodsEntity.setEmail(email);
            goodsEntity.setTelphoneNo(telPhoneNo);
            goodsEntity.setMsn(msn);
            goodsEntity.setQq(qq);
            goodsEntity.setThankWay(thankWay);
            goodsEntity.setFindGoodsQuestion1(findGoodsQuestion1);
            goodsEntity.setFindGoodsQuestion2(findGoodsQuestion2);
            goodsEntity.setFindGoodsQuestion3(findGoodsQuestion3);
            goodsEntity.setFindGoodsAnswer1(findGoodsAnswer1);
            goodsEntity.setFindGoodsAnswer2(findGoodsAnswer2);
            goodsEntity.setFindGoodsAnswer3(findGoodsAnswer3);
            goodsEntity.setProvince(province);
            goodsEntity.setCity(city);
            goodsEntity.setDistrict(district);
            goodsEntity.setGoodsWay(goodsWay);
            goodsEntity.setThankMoneyAmount(thankMoneyAmount);
            goodsEntity.setGoodsStatus(goodsStatus);
            Long goodsId = goodsService.saveGoodsInfo(goodsEntity);

            for (String reqPath : list) {
                //保图片路径实体
                PicUrlEntity picUrlEntity = new PicUrlEntity();
                picUrlEntity.setGoodsPicUrl(reqPath);
                picUrlEntity.setGoodsId(goodsId);
                goodsService.savePicUrl(picUrlEntity);
            }
        } catch (IOException e) {
            result = exceptionHandle.exceptionGet(e);
        }
        return result;
    }

    @PostMapping("/getGoodsInfo")
    public Result getGoodsInfo(@RequestBody GoodsInfoVo goodsInfoVo) {
        Result result = ResultUtil.success();
        JSONObject jsonObject = goodsService.getGoodsInfo(goodsInfoVo);
        result.setData(jsonObject);
        return result;
    }

    @PostMapping("/updateGoodsInfo")
    public Result updateGoodsInfo(@RequestBody GoodsInfoVo goodsInfoVo) {
        Result result = ResultUtil.success();
        Long id = goodsInfoVo.getId();
        if (null == id) {
            throw new DescribeException(ExceptionEnum.USER_ID_IS_NULL);
        }
        List<GoodsEntity> list = goodsService.findById(goodsInfoVo.getId());
        if (null == list || list.size() != 1) {
            throw new DescribeException(ExceptionEnum.USER_IS_NULL);
        }
        //保存失物实体
        GoodsEntity goodsEntity = list.get(0);
        try {
            if (null != goodsInfoVo.getStatus()) {
                goodsEntity.setGoodsStatus(goodsInfoVo.getStatus());
            }
            if (null != goodsInfoVo.getTypeOfGoods()) {
                goodsEntity.setTypeOfGoods(goodsInfoVo.getTypeOfGoods());
            }
            if (null != goodsInfoVo.getInfoTittle()) {

                goodsEntity.setInfoTittle(goodsInfoVo.getInfoTittle());
            }
            if (null != goodsInfoVo.getDescription()) {
                goodsEntity.setDescription(goodsInfoVo.getDescription());
            }
            if (null != goodsInfoVo.getLostPlace()) {
                goodsEntity.setLostPlace(goodsInfoVo.getLostPlace());
            }
            if (null != goodsInfoVo.getConcPlace()) {
                goodsEntity.setConcPlace(goodsInfoVo.getConcPlace());
            }
            if (null != goodsInfoVo.getConcPersion()) {
                goodsEntity.setConcPersion(goodsInfoVo.getConcPersion());
            }
            if (null != goodsInfoVo.getPageNo()) {
                goodsEntity.setPhoneNo(goodsInfoVo.getPageNo());
            }
            if (null != goodsInfoVo.getEmail()) {
                goodsEntity.setEmail(goodsInfoVo.getEmail());
            }
            if (null != goodsInfoVo.getTelPhoneNo()) {
                goodsEntity.setTelphoneNo(goodsInfoVo.getTelPhoneNo());
            }
            if (null != goodsInfoVo.getMsn()) {
                goodsEntity.setMsn(goodsInfoVo.getMsn());
            }
            if (null != goodsInfoVo.getQq()) {
                goodsEntity.setQq(goodsInfoVo.getQq());
            }
            if (null != goodsInfoVo.getThankWay()) {
                goodsEntity.setThankWay(goodsInfoVo.getThankWay());
            }
            if (null != goodsInfoVo.getFindGoodsQuestion1()) {
                goodsEntity.setFindGoodsQuestion1(goodsInfoVo.getFindGoodsQuestion1());
            }
            if (null != goodsInfoVo.getFindGoodsQuestion2()) {
                goodsEntity.setFindGoodsQuestion2(goodsInfoVo.getFindGoodsQuestion2());
            }
            if (null != goodsInfoVo.getFindGoodsQuestion3()) {
                goodsEntity.setFindGoodsQuestion3(goodsInfoVo.getFindGoodsQuestion3());
            }
            if (null != goodsInfoVo.getFindGoodsAnswer1()) {
                goodsEntity.setFindGoodsAnswer1(goodsInfoVo.getFindGoodsAnswer1());
            }
            if (null != goodsInfoVo.getFindGoodsAnswer2()) {
                goodsEntity.setFindGoodsAnswer2(goodsInfoVo.getFindGoodsAnswer2());
            }
            if (null != goodsInfoVo.getFindGoodsAnswer3()) {
                goodsEntity.setFindGoodsAnswer3(goodsInfoVo.getFindGoodsAnswer3());
            }
            if (null != goodsInfoVo.getProvince()) {
                goodsEntity.setProvince(goodsInfoVo.getProvince());
            }
            if (null != goodsInfoVo.getCity()) {
                goodsEntity.setCity(goodsInfoVo.getCity());
            }
            if (null != goodsInfoVo.getDistrict()) {
                goodsEntity.setDistrict(goodsInfoVo.getDistrict());
            }
            if (null != goodsInfoVo.getGoodsWay()) {
                goodsEntity.setGoodsWay(goodsInfoVo.getGoodsWay());
            }
            if (null != goodsInfoVo.getThankMoneyAmount()) {
                goodsEntity.setThankMoneyAmount(goodsInfoVo.getThankMoneyAmount());
            }
            Long goodsId = goodsService.saveGoodsInfo(goodsEntity);
        } catch (Exception e) {
            result = exceptionHandle.exceptionGet(e);
        }

        return result;
    }

    @PostMapping("/delGoods")
    public Result delGoods(HttpServletRequest request, @RequestBody List<String> goodsIds) {
        Result result = ResultUtil.success();
        String path = request.getSession().getServletContext().getRealPath("/") + "images\\upload\\";
        JSONObject jsonObject = goodsService.delGoodsInfo(path, goodsIds);
        result.setData(jsonObject);
        return result;
    }

    @GetMapping("/findAllProvince")
    public Result findAllProvince() {
        Result result = ResultUtil.success();
        String s = goodsService.findAllProvince();
        if (StringUtils.isEmpty(s)) {
            throw new DescribeException(ExceptionEnum.PROVINCE_IS_NULL);
        }
        result.setData(s);
        return result;
    }

    @GetMapping("/findCityByProvince/{provinceId}")
    public Result findCityByProvince(@PathVariable("provinceId") Integer provinceId) {
        Result result = ResultUtil.success();
        String s = goodsService.findCityByProvince(provinceId);
        if (StringUtils.isEmpty(s)) {
            throw new DescribeException(ExceptionEnum.CITY_IS_NULL);
        }
        result.setData(s);
        return result;

    }

    @GetMapping("/findAreaByCity/{cityId}")
    public Result findAreaByCity(@PathVariable("cityId") Integer cityId) {
        Result result = ResultUtil.success();
        String s = goodsService.findAreaByCity(cityId);
        if (StringUtils.isEmpty(s)) {
            throw new DescribeException(ExceptionEnum.DISTRACT_IS_NULL);
        }
        result.setData(s);
        return result;
    }

    @PostMapping("/answerQuestion")
    public Result answerQuestion(@RequestBody AnswerVo answerVo) {
        Result result = ResultUtil.success();
        JSONObject jsonObject = goodsService.answerQuestion(answerVo);
        result.setData(jsonObject);
        return result;
    }


    @GetMapping("/getQuestion/{goodId}")
    public Result leaveMessage(@PathVariable("goodId") Long goodId) {
        Result result = ResultUtil.success();
        JSONObject jsonObject = goodsService.getQuestion(goodId);
        result.setData(jsonObject);
        return result;
    }

    @PostMapping("/leaveMessage")
    public Result leaveMessage(@Valid @RequestBody MessageVo messageVo, BindingResult bindingResult) {
        Result result = ResultUtil.success();
        //参数校验
        if (bindingResult.hasErrors()) {
            List<ObjectError> errorList = bindingResult.getAllErrors();
            for (ObjectError error : errorList) {
                ExceptionEnum.PARAMETER_WRONG.setMsg(error.getDefaultMessage());
                return ResultUtil.error(ExceptionEnum.PARAMETER_WRONG);
            }
        }
        try {
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setGoodsId(messageVo.getGoodsId());
            messageEntity.setMessage(messageVo.getMessage());
            messageEntity.setLeaveTime(new Date());
            messageEntity.setUserId(messageVo.getUserId());
            goodsService.leaveMessage(messageEntity);
        } catch (Exception e) {
            result = exceptionHandle.exceptionGet(e);
        }
        return result;
    }

    @GetMapping("/getMessage/{goodsId}/{pageNo}/{pageSize}")
    public Result getMessage(@PathVariable String goodsId, @PathVariable String pageNo, @PathVariable String pageSize) {
        Result result = ResultUtil.success();
        try {
            JSONObject jsonObject = goodsService.getMessages(goodsId, pageNo, pageSize);
            result.setData(jsonObject);
        } catch (Exception e) {
            result = exceptionHandle.exceptionGet(e);
        }
        return result;
    }

    public String getIP() {
        String ip = "http://ip.chinaz.com/getip.aspx";

        String inputLine = "";
        String read = "";
        try {
            URL url = new URL(ip);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            while ((read = in.readLine()) != null) {
                inputLine += read;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputLine;
    }


}
